#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Desc: NLP task

import re
import os


def NLP_handle(fp):

    if os.path.exists(fp):
        with open(fp, 'r') as files:
            rdfile = files.read().lower()
        f_list = re.split('[,\n\s.!]+', rdfile)
        f_dict = {}
        for i in f_list:
            if i not in f_dict:
                f_dict[i] = 0
            f_dict[i] += 1

        f_dict = sorted(f_dict.items(), key=lambda kv: kv[1])
        print('f_dict is: ', f_dict)
        
        try:
            with open('./out.txt', 'w') as wf:
                for k, v in f_dict:
                    wf.write('{}: {}\n'.format(k, v))
        except Exception as e:
            print(e)
        else:
            print('NLP task is successful')


if __name__ == '__main__':
    PATH = lambda p: os.path.abspath(os.path.join(os.path.dirname(__file__), p))
    fp = PATH('./input.txt')
    NLP_handle(fp)
